/************************************
 * Package: RGcpp					*
 * Authors: Rui Eduardo Gouveia Gil	*
 * Date: 2010						*
 ************************************/
#include "rgcpp/structs/FileLock.h"
#ifndef _WIN32
#include <sys/file.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <cerrno>

namespace rgcpp
{

FileLock::FileLock(std::string aFilePath, EFileLockMode aMode) : filePath(aFilePath), mode(aMode)
{
	this->lock();
}

FileLock::~FileLock()
{
	this->unlock();
}

void FileLock::lock()
{
	if((this->lockFd=open(this->filePath.c_str(), O_CREAT|O_WRONLY, S_IRUSR|S_IWUSR))<0)
		Throw(MissingResourceException(std::string("Failed to open file ")+this->filePath));

	if(flock(this->lockFd,(int)this->mode))
		Throw(SystemException(std::string("flock failed, bad things will happen: ")+strerror(errno)));
}

void FileLock::unlock()
{
	flock(this->lockFd,(int)LOCK_NONE);
	close(this->lockFd);
}

}
#endif